<template>
  <div class="user">
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="5" class="user__tree">
          <avue-tree
            :option="treeOption"
            :data="treeData"
            @node-click="nodeClick"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="19" class="user__main">
          <avue-crud
            ref="crud"
            :option="option"
            v-model="form"
            :page="page"
            :table-loading="listLoading"
            :before-open="handleOpenBefore"
            :data="list"
            @on-load="getList"
            @search-change="handleFilter"
            @refresh-change="handleRefreshChange"
            @row-update="update"
            @search-reset="searchReset"
            @row-save="create"
          >
            <template slot="menuLeft">
              <el-button
                v-if="sys_user_add"
                class="filter-item"
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="handleCreate"
                >添加
              </el-button>
              <el-button
                class="filter-item"
                type="primary"
                size="mini"
                @click="editPWD"
                v-if="sys_user_updatebatch_password || sys_user_del"
                >批量初始密码
              </el-button>
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"
                @click="editEnable('0')"
                v-if="sys_user_updatebatch_lockflag || sys_user_del"
                >批量启用用户
              </el-button>
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"
                @click="editEnable('9')"
                v-if="sys_user_updatebatch_lockflag || sys_user_del"
                >批量锁定用户
              </el-button>
	      <el-button
                class="filter-item"
                type="primary"
                size="mini"
                @click="editEnable('8')"
                v-if="sys_user_updatebatch_lockflag || sys_user_del"
                >批量禁用用户
              </el-button>
            </template>
            <template slot="username" slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
            <template slot="role" slot-scope="scope">
              <span v-for="(role, index) in scope.row.roleList" :key="index">
                <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="deptId" slot-scope="scope">
              {{ scope.row.deptName }}
            </template>
            <template slot="lockFlag" slot-scope="scope">
              <el-tag>{{ scope.label }}</el-tag>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button
                v-if="sys_user_edit"
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row, scope.index)"
                >编辑
              </el-button>
              <el-button
                v-if="sys_user_del"
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="deletes(scope.row,scope.index)">删除
              </el-button>
            </template>
            <template slot="deptIdForm" slot-scope="scope">
              <avue-input-tree
                v-model="form.deptId"
                :node-click="getNodeData"
                :dic="treeDeptData"
                :props="defaultProps"
                type="tree"
                placeholder="请选择所属部门"
              />
            </template>
            <template slot="roleForm" slot-scope="scope">
              <avue-select
                v-model="role"
                :dic="rolesOptions"
                :props="roleProps"
                placeholder="请选择角色"
              />
            </template>
            <template slot="deviceOperateNoForm" slot-scope="scope">
              <el-select v-model="form.deviceOperateNo" placeholder="请选择" allowCreate clearable filterable>
                <el-option
                  v-for="item in deviceList"
                  :key="item.operationCode"
                  :label="item.operationCode"
                  :value="item.operationCode"
                >
                </el-option>
              </el-select>
            </template>

            <template slot="manageStationsForm" slot-scope="scope">
              <dynamic-crud
                title="管理线路与站点"
                :data="form.manageStations"
                :option="stationsOption"
                :disabled="window.boxType == 'view'"
              >
              </dynamic-crud>
            </template>
            <!-- <template slot="menuLeft">
              <el-upload
                class="upload-inline"
                action=""
                :show-file-list="false"
                accept=".xls,.xlsx"
                :http-request="handleImport"
              >
                <el-button type="primary" size="small">导入</el-button>
              </el-upload>
            </template> -->
            <template slot="menuLeft">
              <el-upload
                class="upload-inline"
                action=""
                :show-file-list="false"
                accept=".xls,.xlsx"
                :http-request="handleImportJD"
              >
                <el-button type="primary" size="small">机电导入</el-button>
              </el-upload>
            </template>
            <template slot="menuLeft">
              <el-upload
                class="upload-inline"
                action=""
                :show-file-list="false"
                accept=".xls,.xlsx"
                :http-request="handleImportKY"
              >
                <el-button type="primary" size="small">客运导入</el-button>
              </el-upload>
            </template>
            <template slot="menuRight">
              <el-button
                @click="handleDownloadClickJD"
                type="text"
                size="small"
              >机电模板</el-button>
              <el-button
                @click="handleDownloadClickKY"
                type="text"
                size="small"
              >客运模板</el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
import {
  addObj,
  delObj,
  fetchList,
  putObj,
  saveBatch,
  updateBatch,
  updateBatchLock,
  getUserDeviceNoByCondition,
  templateJD,
  userImportJD,
  templateKY,
  userImportKY
} from "@/api/admin/user";
import { deptRoleList } from "@/api/admin/role";
import { fetchTree } from "@/api/admin/dept";
import { tableOption } from "@/const/crud/admin/user";
import { handleExcelResponse } from "@/util/util";
import { mapGetters } from "vuex";
import {validateDeviceOperateNo} from "@/util/validate";

export default {
  name: "SysUser",
  data() {
    return {
      window: window,
      searchForm: {},
      treeOption: {
        nodeKey: "id",
        addBtn: false,
        menu: false,
        props: {
          label: "name",
          value: "id"
        }
      },
      treeData: [],
      option: tableOption,
      treeDeptData: [],
      checkedKeys: [],
      roleProps: {
        label: "roleName",
        value: "roleId"
      },
      defaultProps: {
        label: "name",
        value: "id"
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      rolesOptions: [],
      deviceList: [],
      stationsOption: {
        column: [
          {
            label: "线路",
            prop: "line",
            type: "select",
            cascaderItem: ["station"],
            props: {
              label: "name",
              value: "code"
            },
            dicUrl: "/support/swparamline/dict",
            cell: true,
            rules: [{ required: true, message: "请选择线路", trigger: "blur" }]
          },
          {
            label: "站点",
            prop: "station",
            type: "select",
            dicFlag: false,
            props: {
              label: "name",
              value: "code"
            },
            dicUrl: "/support/swparamstation/dict/{{key}}",
            cell: true
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  watch: {
    role() {
      this.form.role = this.role ? [this.role] : [];
    },
    "form.belongToLine"(val) {
      this.findObject(this.option.column, "lineCode").display = !val;
      this.findObject(this.option.column, "stationCode").display = !val;
      this.findObject(this.option.column, "deviceOperateNo").display = !val;

      //如果是非线网人员，也可以设置管辖线路
      //this.findObject(this.option.column, "isManageStation").display = val;
      if (val) {
        // 线网人员，线路,车站和设备操作号为空
        this.form.lineCode = null;
        this.form.stationCode = null;
        this.form.deviceOperateNo = null;
      } else {
        if (this.validatenull(this.form.manageStations)) {
          this.form.isManageStation = false;
          this.form.managementLineStation = null;
        }else{
          this.form.isManageStation = true;
        }
      }
    },
    "form.isManageStation"(val) {
      this.findObject(this.option.column, "manageStations").display = val;
    }
  },
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];
    this.sys_user_updatebatch_password = this.permissions["sys_user_updatebatch_password"];
    this.sys_user_updatebatch_lockflag = this.permissions["sys_user_updatebatch_lockflag"];
    this.init();
    const that = this;
    this.option.column[8].change = function(row, col) {
      that.form.deviceOperateNo = "";
      that.deviceList = [];
    };
    this.option.column[9].change = function(row, col) {
      const lineCode = that.form.lineCode;
      const stationCode = row.value;
      if (lineCode && stationCode) {
        getUserDeviceNoByCondition(lineCode, stationCode).then(res => {
          if (res && res.data.data.records.length) {
            if (that.form.deviceOperateNo == '' || that.form.deviceOperateNo == null) {
              that.form.deviceOperateNo = that.form.deviceOperateNoVal
            }
            that.deviceList = res.data.data.records;
          }
        });
      } else {
        that.form.deviceOperateNo = "";
        that.deviceList = [];
      }
    };
  },
  methods: {
    init() {
      fetchTree().then(response => {
        this.treeData = response.data.data;
      });
    },
    nodeClick(data) {
      this.page.page = 1;
      this.getList(this.page, { deptId: data.id });
    },
    handleImport(item) {
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
      saveBatch(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000
        });
        this.getList(this.page);
      });
    },
    async handleDownloadClickJD () {//机电人员导出模板
      this.uploading = true;
      try {
        const res = await templateJD();
        handleExcelResponse(res);
      } finally {
        this.uploading = false;
      }
    },
    handleImportJD(item) {//机电人员导入
      this.$message.info("正在导入，请耐心等待！");
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
     /*
      userImportJD(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000
        });
        this.getList(this.page);
      });*/
      userImportJD(param).then(() => {
          this.$notify({
            title: "成功",
            message: "全部导入成功",
            type: "success",
            duration: 2000
          });
        })
       .catch(error=> {
	  this.$notify({
            title: "失败",
            message: error,
            type: "error",
            duration: 0
          });
        });
	this.getList(this.page);
        done();
    },
    async handleDownloadClickKY () {//客运人员导出模板
      this.uploading = true;
      try {
        const res = await templateKY();
        handleExcelResponse(res);
      } finally {
        this.uploading = false;
      }
    },
    handleImportKY(item) {//客运人员导入
      this.$message.info("正在导入，请耐心等待！");
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
      /*
      userImportKY(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000,
        });
        this.getList(this.page);
      });*/
      userImportKY(param).then(() => {
          this.$notify({
            title: "成功",
            message: "全部导入成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(error=> {
	  this.$notify({
            title: "失败",
            message: error,
            type: "error",
            duration: 0
          });
          //loading();  str.replace(/\n/g, "<br>\n");
        });
	this.getList(this.page);
        done();
    },
    getList(page, params) {
      this.listLoading = true;
      return fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      ).then(response => {
        let records = response.data.data.records;
        records.forEach(r => {
          if (r.managementLineStation) {
            r.isManageStation = true;
            r.manageStations = JSON.parse(r.managementLineStation);
            r.manageStations.forEach(s => {
              s.$cellEdit = true;
            });
          } else {
            r.isManageStation = false;
            r.manageStations = [];
          }
        });
        this.list = records;
        this.page.total = response.data.data.total;
        this.listLoading = false;
      });
    },
    getNodeData() {
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
      });
    },
    handleDept() {
      fetchTree().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    handleFilter(param, done) {
      this.searchForm = param;
      this.getList(this.page, param).then(() => {
        done();
      });
    },
    handleRefreshChange() {
      this.getList(this.page);
    },
    handleCreate() {
      this.$refs.crud.rowAdd();
    },
    handleOpenBefore(show, type) {
      window.boxType = type;
      this.handleDept();
      if (["edit", "view"].includes(type)) {
        for (var i = 0; i < this.form.roleList.length; i++) {
          this.role = this.form.roleList[i].roleId;
          this.form.role = [this.role];
        }
      } else if (type === "add") {
        this.role = null;
        this.form.belongToLine = false;
      }
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
      });
      show();
    },
    handleUpdate(row, index) {
      this.$confirm("修改时如果变更中心站记得修改对应车站所属部门!", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          this.$refs.crud.rowEdit(row, index);
          this.form.password = undefined;
      });
    },
    create(row, done, loading) {
      // if (this.form.phone.indexOf('*') > 0) {
      //     this.form.phone = undefined
      // }
      if (this.validatenull(this.form.manageStations)) {
        this.form.managementLineStation = null;
      } else {
        let lineStations = this.form.manageStations.map(r => {
          return {
            line: r.line,
            station: r.station
          };
        });
        this.form.managementLineStation = JSON.stringify(lineStations);
      }
      if (this.form.lineCode != '' && this.form.lineCode != null
        && this.form.stationCode != '' && this.form.stationCode != null
        && !this.form.username.includes("备用号")) {
        if (this.form.deviceOperateNo == '') {
          this.$message.error("设备操作号不能为空！");
          loading();
          return;
        }
        if (!validateDeviceOperateNo(this.form.deviceOperateNo)) {
          this.$message.error("设备操作号必须为09开头的6位纯数字！");
          loading();
          return false;
        }
      }
      delete this.form.manageStations;
      delete this.form.dates1;
      if (this.form.role == 2 || this.form.role == 3) {
        if (!this.form.isManageStation) {
          this.$message.error("中心站长、副站长，是否管辖线路、车站必须选择'是'！");
          loading();
          return false;
        }
      }
      addObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(() => {
          loading();
        });
    },
    //变更启动、禁用 、锁定   flag ：  8 禁用  0：启用
    editEnable(flag){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let tipValue ="禁用";
      if(flag == '0'){
          tipValue = "启用";
      }
      if(flag == '9'){
          tipValue = "锁定";
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.userId);
      }
      if(ids==null || ids.length==0 ){
        return;
      }
      this.$confirm("确认"+tipValue+"?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
         let str = ids.join(','); // 使用逗号作为分隔符
         updateBatchLock(str,flag)
          .then(data => {
            this.$message.success(tipValue+"成功");
            done();
          })
          .catch(() => {
            loading();
          });
	  this.getList(this.page);
      });
    },
    editPWD: function() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
	ids.push(table.userId);
      }
      if(ids==null || ids.length==0 ){
        return;
      }
      this.$confirm("确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let str = ids.join(','); // 使用逗号作为分隔符
        updateBatch(str)
          .then(data => {
            this.$message.success("修改成功");
            done();
          })
          .catch(() => {
            loading();
          });
         this.getList(this.page);
      });
    },
    update(row, index, done, loading) {
      // if (this.form.phone && this.form.phone.indexOf('*') > 0) {
      //     this.form.phone = undefined
      // }
      if (this.validatenull(this.form.manageStations)) {
        this.form.managementLineStation = null;
      } else {
        let lineStations = this.form.manageStations.map(r => {
          return {
            line: r.line,
            station: r.station
          };
        });
        this.form.managementLineStation = JSON.stringify(lineStations);
      }
      if (this.form.lineCode != '' && this.form.lineCode != null
        && this.form.stationCode != '' && this.form.stationCode != null
        && !this.form.username.includes("备用号")) {
        if (this.form.deviceOperateNo == '') {
          this.$message.error("设备操作号不能为空！");
          loading();
          return;
        }
        if (!validateDeviceOperateNo(this.form.deviceOperateNo)) {
          this.$message.error("设备操作号必须为09开头的6位纯数字！");
          loading();
          return false;
        }
      }
      delete this.form.manageStations;
      delete this.form.dates1;
      if (this.form.roleList[0].roleCode == 'ZXZZ' || this.form.roleList[0].roleCode == 'ZXFZZ') {
        if (!this.form.isManageStation) {
          this.$message.error("中心站长、副站长，是否管辖线路、车站必须选择'是'！");
          loading();
          return false;
        }
      }
      putObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        })
        .catch(() => {
          loading();
        });
    },
    searchReset(form) {
      for (let key of Object.keys(form)) {
        if (this.validatenull(form[key])) {
          delete form[key];
        }
      }
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    deletes(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.list.splice(index, 1);
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .cache(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
.custom-height{
   height: 400px;
   widht: 400px;
   white-space: pre-wrap; /* 或者 normal */
   word-wrap: break-word;
}
</style>
